/*
 * @description 用户管理 - 用户列表
 * @fileName user-index.js
 * @date 2025/07/29 15:22:20
 */

/**
 * user-index.js 只为对权限设置做操作; 不涉及其他内容变更
 */

function CustomPermissionSetting() {
  const $ = layui.$

  let parentConf = null
  let userConf = null
  let _userId = undefined

  return {
    // 获取当前用户权限
    getBaseInfo: function (userId, callback) {
      _userId = userId
      const URL = `/app/admin/v1-api/getUserExtend?user_id=${userId}`
      $.ajax({
        url: URL,
        type: 'get',
        success: function (res) {
          if (res.code) {
            layer.msg(res.msg)
            layui.layer.closeAll('loading')
            return
          }
          const { parent_user_extend, user_extend } = res.data
          parentConf = parent_user_extend
          userConf = user_extend
          callback && callback()
        },
      })
    },
    renderTabHeader: function (list) {
      const fragment = new DocumentFragment()
      $.each(list, function (index, item) {
        fragment.append(
          $(
            `<li class="${index === 0 ? 'layui-this' : ''}">${item.name}</li>`
          )[0]
        )
      })
      $('#promotion-tab').html(fragment)
    },

    // 格式化表单数据 处理 `switch` on|off 问题
    formatFormData: function (formData) {
      // 额外处理 switch 字段
      const keys = [
        'test_switch',
        'test2h_switch',
        'test6h_switch',
        'test12h_switch',
        'rp_switch',
        'zp_switch',
        'yp1_switch',
        'yp3_switch',
        'yp6_switch',
        'np_switch',
        'order_node_refund_switch',
      ]

      for (const key in formData) {
        if (key.endsWith('_switch')) {
          const value = formData[key]
          if (['on', 'off'].includes(value)) {
            formData[key] = value === 'on' ? '1' : '0'
          } else continue
        }
      }

      for (const key of keys) {
        if (!(key in formData)) {
          formData[key] = '0'
        }
      }

      return formData
    },

    renderTabContent: function () {
      const emptyList = [].concat(parentConf)

      const dataList = [].concat(userConf)

      const form = layui.form
      const fragment = new DocumentFragment()
      const $parent = $('#promotion-tab-contact')
      $parent.html('')

      $.each(emptyList, function (index, _item) {
        let item = Object.assign({}, _item)

        // 如果是编辑执行
        if (dataList && dataList.length) {
          const temps = dataList.find((item) => item.line_id === _item.line_id)
          if (temps) {
            const keys = [
              'rp_show',
              'zp_show',
              'yp1_show',
              'yp3_show',
              'yp6_show',
              'np_show',
            ]

            // 此处采用父级配置的是否展示
            const vals = keys.reduce(
              (pre, key) => ({
                ...pre,
                [key]: _item[key],
              }),
              {}
            )
            item = Object.assign({}, item, temps, vals)
          }
        }

        fragment.append(
          $(`<div class="layui-tab-item ${index === 0 ? 'layui-show' : ''}">
          <form class="layui-form" lay-filter="promotion_${index}" data-id="${
            item.line_id
          }">
            <!-- 允许测试卡 -->
            <div class="layui-form-item">
              <div class="layui-form-label">允许测试卡</div>
              <div class="layui-input-block">
                <input type="checkbox" name="test_switch" lay-skin="switch"
                lay-filter="test_switch"
                ${item.test_switch == '1' ? 'checked' : ''}
                />
              </div>
            </div>

            <!-- 允许开2小时 -->
            <div class="layui-form-item test-switch-hours"
              style="display:${item.test_switch == '1' ? '' : 'none'}"
            >
              <div class="layui-form-label">允许开2小时</div>
              <div class="layui-input-block">
                <input type="checkbox" name="test2h_switch" lay-skin="switch"
                ${item.test2h_switch == '1' ? 'checked' : ''}
                />
              </div>
            </div>

            <!-- 允许开6小时 -->
            <div class="layui-form-item test-switch-hours"
              style="display:${item.test_switch == '1' ? '' : 'none'}"
            >
              <div class="layui-form-label">允许开6小时</div>
              <div class="layui-input-block">
                <input type="checkbox" name="test6h_switch" lay-skin="switch"
                ${item.test6h_switch == '1' ? 'checked' : ''}
                />
              </div>
            </div>

            <!-- 允许开12小时 -->
            <div class="layui-form-item test-switch-hours"
              style="display:${item.test_switch == '1' ? '' : 'none'}"
            >
              <div class="layui-form-label">允许开12小时</div>
              <div class="layui-input-block">
                <input type="checkbox" name="test12h_switch" lay-skin="switch" 
                ${item.test12h_switch == '1' ? 'checked' : ''}
                />
              </div>
            </div>

            <!-- 测试卡数量 -->
            <div class="layui-form-item">
              <div class="layui-form-label">测试卡数量</div>
              <div class="layui-input-block">
                <input
                  name="test_number"
                  type="number"
                  min="0"
                  placeholder="请输入测试卡数量"
                  autocomplete="off"
                  class="layui-input"
                  value="${item.test_number ?? ''}"
                />
              </div>
            </div>

            <!-- 最大调换数量 -->
            <div class="layui-form-item">
              <div class="layui-form-label">最大调换数量</div>
              <div class="layui-input-block">
                <input
                  name="max_exchange_number"
                  type="number"
                  min="0"
                  max=${_item.max_exchange_number ?? 999}
                  placeholder="请输入最大调换数量"
                  autocomplete="off"
                  class="layui-input"
                  value="${item.max_exchange_number ?? ''}"
                />
              </div>
            </div>

            <!-- 日卡 -->
            <div class="layui-form-item">
              <div class="layui-form-label">日卡</div>
              <div class="layui-input-block">
                <div class="crow">
                  <input
                    name="rp"
                    type="number"
                    min="${_item.rp ?? 0}"
                    placeholder="请输入日卡价格"
                    autocomplete="off"
                    class="layui-input"
                    value="${item.rp ?? ''}"
                  />
                  <span>官方价格：${_item.rp ?? 0}</span>
                </div>
              </div>
            </div>

            <!-- 周卡 -->
            <div class="layui-form-item">
              <div class="layui-form-label">周卡</div>
              <div class="layui-input-block">
                <div class="crow">
                  <input
                    name="zp"
                    type="number"
                    min="${_item.zp ?? 0}"
                    placeholder="请输入周卡价格"
                    autocomplete="off"
                    class="layui-input"
                    value="${item.zp ?? ''}"
                  />
                  <span>官方价格：${_item.zp ?? 0}</span>
                </div>
              </div>
            </div>

            <!-- 月卡 -->
            <div class="layui-form-item">
              <div class="layui-form-label">月卡</div>
              <div class="layui-input-block">
                <div class="crow">
                  <input
                    type="number"
                    name="yp1"
                    min="${_item.yp1 ?? 0}"
                    placeholder="请输入月卡价格"
                    autocomplete="off"
                    class="layui-input"
                    value="${item.yp1 ?? ''}"
                  />
                  <span>官方价格：${_item.yp1 ?? 0}</span>
                </div>
              </div>
            </div>

            <!-- 季卡 -->
            <div class="layui-form-item">
              <div class="layui-form-label">季卡</div>
              <div class="layui-input-block">
                <div class="crow">
                  <input
                    type="number"
                    name="yp3"
                    min="${_item.yp3 ?? 0}"
                    placeholder="请输入月卡价格"
                    autocomplete="off"
                    class="layui-input"
                    value="${item.yp3 ?? ''}"
                  />
                  <span>官方价格：${_item.yp3 ?? 0}</span>
                </div>
              </div>
            </div>

            <!-- 半年卡 -->
            <div class="layui-form-item">
              <div class="layui-form-label">半年卡</div>
              <div class="layui-input-block">
                <div class="crow">
                  <input
                    type="number"
                    name="yp6"
                    min="${_item.yp6 ?? 0}"
                    placeholder="请输入半年卡价格"
                    autocomplete="off"
                    class="layui-input"
                    value="${item.yp6 ?? ''}"
                  />
                  <span>官方价格：${_item.yp6 ?? 0}</span>
                </div>
              </div>
            </div>
 
            <!-- 年卡 -->
            <div class="layui-form-item">
              <div class="layui-form-label">年卡</div>
              <div class="layui-input-block">
                <div class="crow">
                  <input
                    type="number"
                    name="np"
                    min="${_item.np ?? 0}"
                    placeholder="请输入年卡价格"
                    autocomplete="off"
                    class="layui-input"
                    value="${item.np ?? ''}"
                  />
                  <span>官方价格：${_item.np ?? 0}</span>
                </div>
              </div>
            </div>

            <!-- ====== -->

            <!-- 允许开日卡 -->
            <div class="layui-form-item"
              style="display: ${
                item.rp_show == '1' && _item.rp_switch == '1' ? '' : 'none'
              }"
            >
              <div class="layui-form-label">允许开日卡</div>
              <div class="layui-input-block">
                <input type="checkbox" name="rp_switch" lay-skin="switch"
                ${item.rp_switch == '1' ? 'checked' : ''}
                />
              </div>
            </div>

            <!-- 允许开周卡 -->
            <div class="layui-form-item"
              style="display: ${
                item.zp_show == '1' && _item.zp_switch == '1' ? '' : 'none'
              }"
            >
              <div class="layui-form-label">允许开周卡</div>
              <div class="layui-input-block">
                <input type="checkbox" name="zp_switch" lay-skin="switch"
                ${item.zp_switch == '1' ? 'checked' : ''}
                />
              </div>
            </div>

            <!-- 允许开月卡 -->
            <div class="layui-form-item"
              style="display: ${
                item.yp1_show == '1' && _item.yp1_switch == '1' ? '' : 'none'
              }"
            >
              <div class="layui-form-label">允许开月卡</div>
              <div class="layui-input-block">
                <input type="checkbox" name="yp1_switch" lay-skin="switch" 
                ${item.yp1_switch == '1' ? 'checked' : ''}
                />
              </div>
            </div>

            <!-- 允许开季卡 -->
            <div class="layui-form-item"
              style="display: ${
                item.yp3_show == '1' && _item.yp3_switch == '1' ? '' : 'none'
              }"
            >
              <div class="layui-form-label">允许开季卡</div>
              <div class="layui-input-block">
                <input type="checkbox" name="yp3_switch" lay-skin="switch"
                  ${item.yp3_switch == '1' ? 'checked' : ''}
                />
              </div>
            </div>

            <!-- 是否允许开半年卡 -->
            <div class="layui-form-item" 
              style="display: ${
                item.yp6_show == '1' && _item.yp6_switch == '1' ? '' : 'none'
              }"
            >
              <div class="layui-form-label">允许开半年卡</div>
              <div class="layui-input-block">
                <input type="checkbox" name="yp6_switch" lay-skin="switch"
                  ${item.yp6_switch == '1' ? 'checked' : ''}
                 />
              </div>
            </div>

            <!-- 是否允许开年卡 -->
            <div class="layui-form-item" 
              style="display: ${
                item.np_show == '1' && _item.np_switch == '1' ? '' : 'none'
              }"
            >
              <div class="layui-form-label">允许开年卡</div>
              <div class="layui-input-block">
                <input type="checkbox" name="np_switch" lay-skin="switch"
                  ${item.np_switch == '1' ? 'checked' : ''}
                />
              </div>
            </div>
            
            <!-- 允许节点退款 -->
            <div class="layui-form-item">
              <div class="layui-form-label">允许节点退款</div>
              <div class="layui-input-block">
                <input type="checkbox" name="order_node_refund_switch" lay-skin="switch"
                ${item.order_node_refund_switch == '1' ? 'checked' : ''}
                />
              </div>
            </div>
            
             <!-- 退款时间 -->
            <div class="layui-form-item">
                <div class="layui-form-label">退款时间</div>
              <div class="layui-input-block">
                  <input 
                  name="order_node_refund_time" 
                  type="number" 
                  min="0"
                  placeholder="请输入退款时间"
                  class="layui-input" 
                  value="${item.order_node_refund_time ?? ''}"
                  />
                  <div style="color: red">单位：小时 节点购买后退款时间</div>
              </div>
            </div>
            
            <!-- 退款数量 -->
            <div class="layui-form-item">
              <div class="layui-form-label">退款数量</div>
              <div class="layui-input-block">
                <input
                  name="order_node_refund_number"
                  type="number"
                  min="0"
                  placeholder="请输入退款数量"
                  autocomplete="off"
                  class="layui-input"
                  value="${item.order_node_refund_number ?? ''}"
                />
                <div style="color: red">每天节点退款数量</div>
              </div>
            </div>
            
            <div class="layui-form-item">
              <div class="layui-input-block">
                <div class="tips">
                  <i
                    >我的价格：月卡 <span>${_item.yp1}</span> 金币 周卡
                    <span>${_item.zp}</span> 金币 天卡 <span>${
            _item.rp
          }</span> 金币</i
                  >
                </div>
              </div>
            </div>
          </form></div>`)[0]
        )
      })

      $parent.html(fragment)

      setTimeout(function () {
        // 渲染 form tab - switch element.
        form.render() // 渲染全部

        form.on('switch(test_switch)', function (data) {
          const $curForm = $(
            '#promotion-tab-contact .layui-tab-item.layui-show form'
          )
          $.each($curForm.find('.test-switch-hours'), function (index, item) {
            const bool = $(item).is(':hidden')
            if (!bool) {
              $(item).find('input:checkbox').removeAttr('checked')
              form.render('checkbox') // rerender element.
            }
            $(item)[bool ? 'show' : 'hide']()
          })
        })
      }, 60)
    },

    // 渲染内容
    renderContact: function () {
      this.renderTabHeader(parentConf)
      this.renderTabContent()
    },

    // save apis
    saveFormData: function (datas, callback) {
      const _that = this
      let URL = `/app/admin/v1-api/editUserExtend`
      const params = [`user_id=${_userId}`, `data=${JSON.stringify(datas)}`]
      URL += `?${params.join('&')}`

      layer.load()
      $.ajax({
        url: URL,
        type: 'GET',
        success: function (res) {
          layer.closeAll('loading')
          layer.msg(res.msg)
          if (res.code) return
          callback && callback()
        },
      })
    },

    // 保存当前表单
    saveCurrentForm: function (callback) {
      const _that = this
      const form = layui.form

      // format event.
      const getFormAttrStr = (formElement, key = 'lay-filter') =>
        $(formElement).attr(key)

      const datas = [] // 过滤的 `formDatas`

      // 获取所有的 tab-contact/
      const $parentTabItems = $('#promotion-tab-contact .layui-tab-item')
      const shows = [
        'rp_show',
        'zp_show',
        'yp1_show',
        'yp3_show',
        'yp6_show',
        'np_show',
      ]
      $.each($parentTabItems, function (index, item) {
        const formElement = $(item).find('form')[0]
        const filterStr = getFormAttrStr(formElement)
        const line_id = getFormAttrStr(formElement, 'data-id')
        const formData = _that.formatFormData(form.val(filterStr))

        // NOTE: `_show` 字段永远跟随上级属性
        const _item = parentConf.find((item) => item.line_id == line_id)
        for (const key of shows) {
          if (!formData[key]) {
            formData[key] = _item[key]
          }
        }

        const data = Object.assign({}, formData, { line_id })
        datas.push(data)
      })

      layer.confirm('确认保存, 是否继续?', function (index) {
        _that.saveFormData(datas, function () {
          layer.close(index)
          callback && callback()
        })
      })
    },
  }
}
